package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.model.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {


    @Autowired(required = false)
    ArticleMapper articleMapper;


    @Autowired
    ArticleContentMapper articleContentMapper;

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ArticleFreemarkerService articleFreemarkerService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private final static short MAX_PAGE_SIZE = 50;
    /**
     *
     * @param loadType 判断是上拉还是下滑 1向上滑 2是向下滑
     * @param dto 查询参数
     * @return
     */
    @Override
    public ResponseResult<?> load(Integer loadType, ArticleHomeDto dto) {
        /*校验参数*/
        Integer size = dto.getSize();
        if(size==null||size==0){
            dto.setSize(10);
        }
        int min = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(min);

        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if(dto.getMinBehotTime()==null)dto.setMinBehotTime(new Date());
        if(dto.getMaxBehotTime()==null)dto.setMaxBehotTime(new Date());

        List<ApArticle> list= articleMapper.load(loadType,dto);
        return ResponseResult.okResult(list);
    }


    /**
     * 保存和修改文章内容+文章配置+文章信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle article =null;
        ApArticleContent apArticleContent=null;
        if(dto.getId()==null){
            //保存文章信息
            article=new ApArticle();
            BeanUtils.copyProperties(dto, article);
            articleMapper.insert(article);
            //保存文章内容
            apArticleContent= new ApArticleContent();
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(article.getId());
            articleContentMapper.insert(apArticleContent);
            //保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(article.getId());
            apArticleConfigMapper.insert(apArticleConfig);
        }else {
            //先查询再修改
            //修改文章信息
            article = articleMapper.selectById(dto.getId());
            if(article!=null){
                BeanUtils.copyProperties(dto, article);
                articleMapper.updateById(article);
                //修改文章内容
                if(dto.getContent()!=null){
                    apArticleContent = articleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
                    apArticleContent.setContent(dto.getContent());
                    articleContentMapper.updateById(apArticleContent);
                }
                //ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, article.getId()));
            }
        }

        if(article.getId()!=null){
            try {
                articleFreemarkerService.buildArticleToMinIO(article,apArticleContent.getContent());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return ResponseResult.okResult(article==null?"":article.getId());
    }

    @Override
    public ResponseResult loadArticleList2(ArticleHomeDto dto) {
        String hotArticleListStr = stringRedisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        //转化类型
        List<HotArticleVo> hotArticleVoList = JSONArray.parseArray(hotArticleListStr, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVoList);
    }
}
